#include <memory.h>
#include <iostream.h>

#include "StringTab.h"
#define MAXLEN 1024

StringTab::StringTab(){
	mFirstStringTabNode = new StringTabNode(MAXLEN);
	mNextFreeCharacter = mFirstStringTabNode->getLexems();
	mFreeSpaceInCurrentStringTabNode = MAXLEN;
}

StringTab::~StringTab(){
	StringTabNode* current = this->mFirstStringTabNode;
	StringTabNode* next;
	while(current != 0){
		next = current->getNext();
		delete current;
		current = next;
	}
}

// Adding new lexem to StringTab
char* StringTab::insert(char* lexem, int size){
	char* startCharacterOfLexem = this->mNextFreeCharacter;
	if(size < mFreeSpaceInCurrentStringTabNode){
		memcpy(this->mNextFreeCharacter, lexem, size + 1);
		this->mNextFreeCharacter[size] = '\0';
		this->mNextFreeCharacter += size+1;
		this->mFreeSpaceInCurrentStringTabNode -= size+1;
	}else{
		// Finding last StringTabNode
		StringTabNode* current = this->mFirstStringTabNode;
		while(current->getNext() != 0){
			current = current->getNext();
		}
		// Creating new StringTabNode
		StringTabNode* newNode = new StringTabNode(MAXLEN);
		current->setNext(newNode);
		this->mNextFreeCharacter = newNode->getLexems();
		startCharacterOfLexem = this->mNextFreeCharacter;

		// Copy lexem to StringTablNode and updating internal info
		memcpy(this->mNextFreeCharacter, lexem, size + 1);
		this->mNextFreeCharacter[size] = '\0';
		this->mNextFreeCharacter += size+1;
		this->mFreeSpaceInCurrentStringTabNode = MAXLEN - size+1;
	}
	return startCharacterOfLexem;
}

void StringTab::printStringTab(){
	std::cout << "Printing all String Tabs:" << std::endl;
	StringTabNode* current = this->mFirstStringTabNode;

	bool run = true;
	while(run){
		for(int i = 0; i < MAXLEN; i++){
			std::cout << current->getLexems()[i];
		}
		std::cout << std::endl;
		current = current->getNext();
		if(current == 0){
			run = false;
		}
	}
}
